<?php
// 应用公共文件

use app\utils\captcha\CaptchaApi;
use think\Paginator;

function hex2rgba($color, $opacity = false, $raw = false)
{
    $default = 'rgb(0,0,0)';
    //Return default if no color provided
    if (empty($color))
        return $default;
    //Sanitize $color if "#" is provided
    if ($color[0] == '#') {
        $color = substr($color, 1);
    }
    //Check if color has 6 or 3 characters and get values
    if (strlen($color) == 6) {
        $hex = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
    } elseif (strlen($color) == 3) {
        $hex = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
    } else {
        return $default;
    }

    //Convert hexadec to rgb
    $rgb =  array_map('hexdec', $hex);

    if ($raw) {
        if ($opacity) {
            if (abs($opacity) > 1) $opacity = 1.0;
            array_push($rgb, $opacity);
        }
        $output = $rgb;
    } else {
        //Check if opacity is set(rgba or rgb)
        if ($opacity) {
            if (abs($opacity) > 1)
                $opacity = 1.0;
            $output = 'rgba(' . implode(",", $rgb) . ',' . $opacity . ')';
        } else {
            $output = 'rgb(' . implode(",", $rgb) . ')';
        }
    }

    //Return rgb(a) color string
    return $output;
}
if (!function_exists('storage_log')) {
    /**
     * @param string $config
     * @return array
     */
    function storage_log($message)
    {
        return file_put_contents(runtime_path("log") . date("Ymd") . ".log", "[" . date("Y-m-d H:i:s") . "]" . $message . PHP_EOL, FILE_APPEND);
    }
}
/**
 * api成功返回
 */
function success($data = [], $msg = 'success', $header = [], $options = [])
{
    return json([
        'data' => $data,
        'msg' => $msg,
        'code' => 200,
    ], 200, $header, $options);
}

/**
 * api成功返回
 */
function successPage($data = null, $msg = 'success', $header = [], $options = [])
{
    if ($data instanceof Paginator) {
        return success([
            'items' => $data->items(),
            'pageSize' => $data->listRows(),
            'pageNum' => $data->currentPage(),
            'total' => $data->total(),
            'totalPage' => $data->lastPage(),
        ]);
    }
    return error('分页数据错误');
}


/**
 * api失败返回
 */
function error($msg = 'error', $data = [], $code = 500)
{
    return json([
        'data' => $data,
        'msg' => $msg,
        'code' => $code,
    ], 200);
}

function check_api_captcha($cache_key, $code)
{
    $result = CaptchaApi::check($cache_key, $code);
    return $result;
}


function makeTree($datas, $idKey = 'id', $pidKey = 'parent_id')
{
    $refer = array();
    $tree = array();
    foreach ($datas as $k => $v) {
        $refer[$v[$idKey]] = &$datas[$k]; //创建主键的数组引用
    }

    foreach ($datas as $k => $v) {
        $pid = $v[$pidKey];  //获取当前分类的父级id
        if (!$pid) {
            $tree[] = &$datas[$k];  //顶级栏目
        } else {
            if (isset($refer[$pid])) {
                $refer[$pid]['children'][] = &$datas[$k]; //如果存在父级栏目，则添加进父级栏目的子栏目数组中
            }
        }
    }
    return count($tree) > 0 ? $tree : $datas;
}
//二维数组获取最值
function searchMin($arr, $field)
{
    if (!is_array($arr) || !$field) { //判断是否是数组以及传过来的字段是否是空
        return false;
    }
    $temp = array();
    foreach ($arr as $key => $val) {
        $temp[] = $val[$field]; // 用一个空数组来承接字段
    }
    return min($temp);  // 用php自带函数 max 来返回该数组的最大值，一维数组可直接用max函数
}
function searchMax($arr, $field)
{
    if (!is_array($arr) || !$field) { //判断是否是数组以及传过来的字段是否是空
        return false;
    }
    $temp = array();
    foreach ($arr as $key => $val) {
        $temp[] = $val[$field]; // 用一个空数组来承接字段
    }
    return max($temp);
}
function generateRouters($trees)
{
    //0 目录 1菜单 2按钮接口
    $new_data = [];
    foreach ($trees as $data) {
        $temp_data = [
            'name' => $data['component'] ? str_replace('/', '', $data['component']) : ucfirst($data['path']),
        ];
        $temp_data['path'] = $data['path'];
        //目录
        if ($data['menu_type'] == 'M' && $data['parent_id'] == 0) {
            //目录
            $temp_data['path'] = "/{$data['path']}";
        }
        //菜单
        if ($data['menu_type'] == 'C' && $data['parent_id'] == 0) {
            $temp_data['path'] = "/";
        }

        $temp_data['hidden'] = $data['visible'] == 0 ? true : false;

        if ($data['menu_type'] == 'M' && isset($data['children']) && count($data['children']) > 0 && $data['parent_id'] > 0) {
            $temp_data['component'] = $data['component'] ? $data['component'] : 'ParentView';
        } else {
            $temp_data['component'] = $data['component'] ? $data['component'] : 'Layout';
        }

        if (isset($data['children']) && count($data['children']) > 0 && $data['menu_type'] === 'M') {
            $temp_data['redirect'] = "noRedirect";
            $temp_data['alwaysShow'] = true;
            $temp_data['children'] = generateRouters($data['children']);
        }
        $temp_data['meta'] = [
            'title'  => $data['menu_name'],
            'icon'  => $data['icon'],
            'noCache'  => $data['is_cache'] ? false : true,
        ];
        $new_data[] = $temp_data;
    }
    return $new_data;
}
